package com.jshx.sz.gdjt.util;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;

public class TDESEncodeUtils {

    private static final String CRYPT_KEY_1 = "??!3fX??";
    private static final String CRYPT_KEY_2 = "yds!ds?f";
    
    public static String encrypt(String value) {
        String result = "";
        try {
            value = java.net.URLEncoder.encode(value, "utf-8");
            result = toEncrypt(value);
        } catch (Exception ex) {
            return "";
        }
        return result;
    }
    
    private static String toEncrypt(String value) {
        String result = "";
        try {
            result = toHexString(encrypt(value, CRYPT_KEY_1)).toUpperCase();
            result = toHexString(encrypt(result, CRYPT_KEY_2)).toUpperCase();
        } catch (Exception ex) {
            return "";
        }
        return result;
    }
    
    private static byte[] encrypt(String message, String key) throws Exception {
        Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");

        DESKeySpec desKeySpec = new DESKeySpec(key.getBytes("UTF-8"));

        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
        SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
        IvParameterSpec iv = new IvParameterSpec(key.getBytes("UTF-8"));
        cipher.init(Cipher.ENCRYPT_MODE, secretKey, iv);

        return cipher.doFinal(message.getBytes("UTF-8"));
    }
    
    private static String toHexString(byte b[]) {
        StringBuffer hexString = new StringBuffer();
        for (int i = 0; i < b.length; i++) {
            String plainText = Integer.toHexString(0xff & b[i]);
            if (plainText.length() < 2)
                plainText = "0" + plainText;
            hexString.append(plainText);
        }
        return hexString.toString();
    }
    
}
